package com.ldan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    @LoadBalanced
    private RestTemplate loadBalancedRestTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping("/sayHello")
    public @ResponseBody String hello() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("hello-server");
        String url = String.format("http://%s:%s",serviceInstance.getHost(),serviceInstance.getPort())+"/hello";
        String response = restTemplate.getForObject(url, String.class);
        return response;
    }

    @RequestMapping("sayHello2")
    public @ResponseBody String hello2() {
        return loadBalancedRestTemplate.getForEntity("http://hello-server/hello", String.class).getBody();
    }

}
